﻿var editor = null;
var $hPara = $('#hPara');
var isSource = $hPara.data('source') == '1';
var classId = $hPara.data('cid');
var threadId = $hPara.data('tid');
var threadType = $hPara.data('threadtype');
var originalTags = $hPara.data('tags');// 原始标签
var isTagChanged = false;
var originalContentType = $hPara.data('contenttype');

$(function () {
    var toolbars=["fontfamily", 
        "fontsize", 
        "forecolor", 
        "backcolor", 
        "bold", 
        "italic", 
        "underline", 
        "undo", 
        "justifyleft", 
        "justifycenter", 
        "justifyright", 
        "link", 
        "unlink", 
        "insertimage",
        "music", 
        "insertvideo", 
        "emotion", 
        "lineheight", 
        "inserttable", 
        "searchreplace"];
    if ($.browser.msie) {
        toolbars.push('snapscreen');
    }
    if(isSource){
        //toolbars.push('|');
        toolbars.push('source');
    }
    
    editor = new UE.ui.Editor({
        toolbars: [toolbars],
        imageUrl: "/service/TopicPicHandler.ashx?action=ueupload",
        imagePath: "",
        snapscreenServerUrl: "/service/TopicPicHandler.ashx?action=ueupload",
        snapscreenPath: "",
        wordCount: false,
        elementPathEnabled: false,
        autoHeightEnabled: false
    });

    editor.render('txtComment');

    // 置顶选项
    $('input[name=r_top]').click(function(){
        if ($("#r_top_days").is(":checked")) {
            $("#t_days").removeAttr("disabled");
        }
        else {
            $("#t_days").attr("disabled", "disabled");
        }
    });

    $("#ddlTagList").live("change", function () {
        $("#hfTag").val($("#ddlTagList option:selected").val());
    });

    //重新编辑标签
    var tag = $("#hfTag").val();
    if (tag != "") {
        if ($('#ddlTagList option[value="' + tag + '"]').length == 0) {
            $("#ddlTagList").find("option").first().before("<option value='" + tag + "' selected>" + tag + "</option>");
        }
        else {
            $('#ddlTagList').val(tag);
        }
    }

    // 选中作业类型
    if (threadId > 0) {        
        $('input[type=radio][name=contentType][value=' + originalContentType + ']').attr('checked', 'checked');
    }

    // 发布帖子
    $("#btnNewTopic").click(function () {
        var valid = chkform();
        if (!valid) return false;

        var contentType = $('input[type=radio][name=contentType]:checked').val();
        if (contentType === undefined) {
            if (threadType == 1) {
                alert('请选择作业类型');
                return;
            }
            else {
                contentType = 1;
            }
        }

        var option = {
            action: 'add',
            classId: classId,
            threadType: threadType,
            contentType: contentType,
            title:$.trim($("#txtTitle").val()),
            content:editor.getContent(),
            tags: $('#ddlTagList').val(),
            threadTopStatusType: $('input[type=radio][name=r_top]:checked').val(),
            isAnswerSheet: $('#IsAnswerSheet').is(':checked') ? 1 : 0,
            topDays: parseInt($('#t_days').val())
        };
        
        if (isPosting) return;

        isPosting = true;
        $("#btnNewTopic").html('发布中...');        
        $.post('/app/handlers/class_thread.ashx', option, function (response) {
            isPosting = false;
            if (response.isSuccess) {
                // 跳转到新发布的帖子页面
                window.location.href = '/topic/' + parseInt(response.data) + '/';
            }
            else {
                $("#btnNewTopic").html('发布');
                hjbox.showerror(response.message);
            }
        });
    });

    // 编辑帖子
    $('#btnEdit').click(function () {
        var valid = chkform();
        if (!valid) return false;

        var contentType = $('input[type=radio][name=contentType]:checked').val();
        if (contentType === undefined) {
            if (threadType == 1) {
                alert('请选择作业类型');
                return;
            }
            else {
                contentType = 1;
            }
        }

        var option = {
            action: 'edit',
            threadId:threadId,
            classId: classId,
            threadType: threadType,
            contentType: contentType,
            title: $.trim($("#txtTitle").val()),
            content: editor.getContent(),
            tags: $('#ddlTagList').val(),
            isTagChanged:$('#ddlTagList').val()!=originalTags?1:0,
            isAnswerSheet: $('#IsAnswerSheet').is(':checked') ? 1 : 0
        };

        if (isPosting) return;

        isPosting = true;
        $('#btnEdit').html('保存中...');
        $.post('/app/handlers/class_thread.ashx', option, function (response) {
            isPosting = false;
            if (response.isSuccess) {
                // 跳转到帖子页面
                window.location.href = '/topic/' + threadId + '/';
            }
            else {
                $('#btnEdit').html('提交修改');
                hjbox.showerror(response.message);
            }
        });
    });

    // 定时发布
    $('#btnAutoPublish').click(function () {
        var valid = chkform();
        if (!valid) return false;

        // 自动发布的时间
        if ($('#hidposttime').val() == '') {
            showAutoTime();
            return;
        }

        var contentType = $('input[type=radio][name=contentType]:checked').val();
        if (contentType === undefined) {
            if (threadType == 1) {
                alert('请选择作业类型');
                return;
            }
            else {
                contentType = 1;
            }
        }

        var option = {
            action: 'auto',
            classId: classId,
            threadType: threadType,
            contentType: contentType,
            title: $.trim($("#txtTitle").val()),
            content: editor.getContent(),
            tags: $('#ddlTagList').val(),
            threadTopStatusType: $('input[type=radio][name=r_top]:checked').val(),
            isAnswerSheet: $('#IsAnswerSheet').is(':checked') ? 1 : 0,
            topDays: parseInt($('#t_days').val()),
            postTime: $('#hidposttime').val()
        };

        if (isPosting) return;

        isPosting = true;
        $("#btnAutoPublish").html('发布中...');
        $.post('/app/handlers/class_thread.ashx', option, function (response) {
            isPosting = false;
            if (response.isSuccess) {
                // 跳转到草稿页面
                window.location.href = '/' + parseInt(classId) + '/mydraft';
            }
            else {
                $("#btnAutoPublish").html('定时发布');
                hjbox.showerror(response.message);
            }
        });
    });

    // 保存草稿
    $('#btnSaveDraft').click(function(){
        var valid = chkform();
        if (!valid) return false;

        var contentType = $('input[type=radio][name=contentType]:checked').val();
        if (contentType === undefined) {
            if (threadType == 1) {
                alert('请选择作业类型');
                return;
            }
            else {
                contentType = 1;
            }
        }

        var option = {
            action: 'save',
            classId: classId,
            threadType: threadType,
            contentType: contentType,
            title: $.trim($("#txtTitle").val()),
            content: editor.getContent(),
            tags: $('#ddlTagList').val(),
            threadTopStatusType: $('input[type=radio][name=r_top]:checked').val(),
            isAnswerSheet: $('#IsAnswerSheet').is(':checked') ? 1 : 0,
            topDays: parseInt($('#t_days').val())
        };

        if (isPosting) return;

        isPosting = true;
        $("#btnSaveDraft").html('正在保存...');
        $.post('/app/handlers/class_thread.ashx', option, function (response) {
            isPosting = false;
            if (response.isSuccess) {
                // 跳转到草稿页面
                window.location.href = '/' + parseInt(classId) + '/mydraft';
            }
            else {
                $("#btnSaveDraft").html('保存草稿');
                hjbox.showerror(response.message);
            }
        });
    });

    $("#txtDate").datepicker($.datepicker.regional["zh-CN"]);
    $("#txtDate").datepicker();

    //Add Tag button
    $("#ddlTagList").append("<option value='-1' class='opLink'>自定义分类</option>");

    //tag changed
    $("#ddlTagList").change(function () {
        if ($(this).val() == -1) {
            $("#pnl_addTag").dialog({ width: 445, height: 140, show: 'fade', hide: 'fade', open: function () { } })
            $(this).val(0);
        }
    });

    //bind closeButton
    $(".btn_closepnlTag").bind("click", function () {
        $(this).parents(".ui-dialog").find(".ui-icon-closethick").click();
    });

    //bind txtTag keyup
    $("#txtAddCate").bind("keydown", function (e) {
        if (e.keyCode == 13) {
            addCate($(this).val());
        }
    });

    $("#btn_addCate").bind("click", function () {
        var tag = $("#txtAddCate").val();
        addCate(tag);
    })

    $("#txtTitle").focus();

    if (threadId > 0) {
        // 获取置顶状态
        getTopStatus();
    }
});

var isPosting = false;

function OpenPreview() {
    centerWin('/'+classId+'/newtopic/preview', 700, 550);
}

function chkform() {

    var html = editor.getContent();
    var filterHtml = filterXSS(html);
    editor.setContent(filterHtml);

    if ($.trim($("#txtTitle").val()) == "") {
        AlertHelper.flickCnt($("#txtTitle"));
        $("#txtTitle").val("").focus();
        return false;
    }

    if ($.trim(editor.getContent().replace(/&nbsp;/g, "").replace(/<br>/g, "").replace(/<br \/>/g, "").replace(/<br\/>/g, "")) == "") {
        hjbox.showerror("内容不能为空", 1500);
        editor.setContent("");
        return false;
    }

    if ($("#ddlTagList").val() == "0" || $("#ddlTagList").val() == "-1") {
        alert("请选择分类");
        return false;
    }
    //$("#btnNewTopic").val("发布中...").attr("disabled", true);
    //if (!isPosting) {
    //    isPosting = true;
    //    return true;
    //}
    //else {
    //    return false;
    //}
    return true;
}

//模式切换
function ChangeState(obj) {
    var url = $(obj).attr("url");
    if (confirm("转换前请确保内容已保存，是否继续")) {
        window.location.href = url;
    }
}

// 添加标签分类
function addCate(tag) {
    tag = $.trim(tag);
    if (tag == "") {
        alert("请填写分类名称");
    }
    else {
        if (!CheckHasTag(tag)) {
            $("#hfTag").val(tag);
            $("#ddlTagList").find("option").last().before("<option>" + tag + "</option>");
            $("#ddlTagList").val(tag);
            $("#txtAddCate").val("");
            $(".ui-dialog").find(".ui-icon-closethick").click();
        }
        else {
            alert("此分类已存在");
        }
    }
}

// 检查是否存在这个分类
function CheckHasTag(tag) {
    //判断是否存在这个分类
    $("#ddlTagList").find("option").each(function () {
        if ($(this).html() == tag) {
            return true;
        }
    });
    return false;
}

// 显示自动发布设置
function showAutoTime() {
    if (chkform()) {
        $("#autotime iframe").attr("src", "/class/topic_mythread_posttime.aspx?cid=" + classId + "&tid=0");
        $("#autotime").dialog({
            modal: true, title: "新发布帖", width: 400, height: 250, show: 'fade', hide: 'fade'
           , resizable: false, close: function () {
               if ($("#hidposttime").val() != "") $("#btnAutoPublish").click();
           }
        });
    }
    return false;
}

// 显示设置置顶
function showSetTop() {
    $("#div_settop iframe").attr("src", "/class/topic_mythread_settop.aspx?tid=" + threadId + "&edit=true");

    $("#div_settop").dialog({
        modal: true, title: '编辑置顶', width: 400, height: 200, show: 'fade', hide: 'fade', resizable: false, close: function () {
            getTopStatus();
        }
    });
    return false;
}

function getTopStatus() {
    //获取最新帖子置顶信息
    $.post('/app/handlers/class_thread.ashx', {
        action: 'top_status',
        threadId: threadId
    }, function (response) {
        if (response.isSuccess) {
            $("#label_topStatus").html(response.data);
        }
    });
}